/**
 * AsciiDoc文档平台 - 前端应用
 * 提供文档管理、预览、搜索等功能
 */

class AsciiDocViewer {
    constructor() {
        this.currentDocId = null;
        this.comments = [];
        this.versions = [];
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupAjax();
    }

    bindEvents() {
        // 全局事件绑定
        document.addEventListener('DOMContentLoaded', () => {
            this.setupFileUpload();
            this.setupSearch();
            this.setupComments();
        });
    }

    setupAjax() {
        // 设置AJAX默认选项
        $.ajaxSetup({
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error);
                this.showError('操作失败：' + error);
            }.bind(this)
        });
    }

    setupFileUpload() {
        const uploadForm = document.getElementById('uploadForm');
        if (!uploadForm) return;

        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.querySelector('.upload-area');

        if (uploadArea) {
            // 拖放上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    fileInput.files = files;
                    this.handleFileSelect(files[0]);
                }
            });
        }

        fileInput?.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleFileSelect(file);
            }
        });
    }

    handleFileSelect(file) {
        // 验证文件类型
        const allowedTypes = ['.adoc', '.asciidoc', '.asc'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        
        if (!allowedTypes.includes(fileExtension)) {
            this.showError('请选择有效的AsciiDoc文件 (.adoc, .asciidoc, .asc)');
            return;
        }

        // 验证文件大小 (16MB)
        if (file.size > 16 * 1024 * 1024) {
            this.showError('文件大小不能超过16MB');
            return;
        }

        // 自动填充标题
        const titleInput = document.getElementById('titleInput');
        if (titleInput && !titleInput.value) {
            const title = file.name.replace(/\.[^/.]+$/, '');
            titleInput.value = title;
        }

        this.showSuccess(`已选择文件：${file.name}`);
    }

    setupSearch() {
        const searchInput = document.getElementById('searchInput');
        if (!searchInput) return;

        let searchTimeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            const query = e.target.value.trim();
            
            if (query.length < 2) {
                this.clearSearch();
                return;
            }

            searchTimeout = setTimeout(() => {
                this.performSearch(query);
            }, 300);
        });

        // 回车搜索
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.performSearch(e.target.value.trim());
            }
        });
    }

    async performSearch(query) {
        if (!this.currentDocId) return;

        try {
            const response = await fetch(`/api/document/${this.currentDocId}/search?q=${encodeURIComponent(query)}`);
            const data = await response.json();
            
            if (data.results) {
                this.displaySearchResults(data.results, query);
            }
        } catch (error) {
            console.error('搜索失败:', error);
            this.showError('搜索失败：' + error.message);
        }
    }

    displaySearchResults(results, query) {
        const iframe = document.getElementById('documentFrame');
        if (!iframe) return;

        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        
        // 清除之前的高亮
        this.clearSearch();

        // 高亮搜索结果
        results.forEach(result => {
            const elements = iframeDoc.querySelectorAll('*');
            elements.forEach(el => {
                if (el.textContent.includes(query)) {
                    this.highlightText(el, query);
                }
            });
        });

        if (results.length > 0) {
            // 滚动到第一个结果
            const firstResult = iframeDoc.querySelector('.search-highlight');
            if (firstResult) {
                firstResult.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }
    }

    highlightText(element, query) {
        const walker = element.ownerDocument.createTreeWalker(
            element,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        const nodes = [];
        let node;
        
        while (node = walker.nextNode()) {
            if (node.textContent.toLowerCase().includes(query.toLowerCase())) {
                nodes.push(node);
            }
        }

        nodes.forEach(textNode => {
            const parent = textNode.parentNode;
            const text = textNode.textContent;
            const regex = new RegExp(`(${query})`, 'gi');
            const newText = text.replace(regex, '<mark class="search-highlight">$1</mark>');
            
            if (newText !== text) {
                const span = document.createElement('span');
                span.innerHTML = newText;
                
                while (span.firstChild) {
                    parent.insertBefore(span.firstChild, textNode);
                }
                
                parent.removeChild(textNode);
            }
        });
    }

    clearSearch() {
        const iframe = document.getElementById('documentFrame');
        if (!iframe) return;

        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        const highlights = iframeDoc.querySelectorAll('.search-highlight');
        
        highlights.forEach(highlight => {
            const parent = highlight.parentNode;
            parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
            parent.normalize();
        });
    }

    setupComments() {
        const commentForm = document.getElementById('commentForm');
        if (!commentForm) return;

        commentForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.addComment();
        });
    }

    async addComment() {
        const commentInput = document.getElementById('commentInput');
        const content = commentInput?.value.trim();
        
        if (!content) {
            this.showError('请输入评论内容');
            return;
        }

        try {
            const response = await fetch(`/api/document/${this.currentDocId}/comments`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    content: content,
                    author: '当前用户'
                })
            });

            const data = await response.json();
            
            if (data.success) {
                this.comments.push(data.comment);
                this.renderComments();
                commentInput.value = '';
                this.showSuccess('评论添加成功');
            }
        } catch (error) {
            this.showError('添加评论失败：' + error.message);
        }
    }

    renderComments() {
        const commentsList = document.getElementById('commentsList');
        if (!commentsList) return;

        commentsList.innerHTML = this.comments.map(comment => `
            <div class="comment">
                <div class="comment-header">
                    <span class="comment-author">${comment.author}</span>
                    <span class="comment-time">${new Date(comment.timestamp).toLocaleString()}</span>
                </div>
                <div class="comment-content">${this.escapeHtml(comment.content)}</div>
            </div>
        `).join('');
    }

    async loadDocument(docId) {
        this.currentDocId = docId;
        
        try {
            // 加载文档内容
            const response = await fetch(`/api/document/${docId}/content`);
            const data = await response.json();
            
            if (data.content) {
                this.renderDocument(data.content);
            }

            // 加载评论
            const commentsResponse = await fetch(`/api/document/${docId}/comments`);
            const commentsData = await commentsResponse.json();
            
            if (commentsData.comments) {
                this.comments = commentsData.comments;
                this.renderComments();
            }
        } catch (error) {
            console.error('加载文档失败:', error);
            this.showError('加载文档失败：' + error.message);
        }
    }

    renderDocument(content) {
        const viewer = document.getElementById('documentViewer');
        if (!viewer) return;

        // 这里应该使用Asciidoctor.js渲染内容
        // 目前使用iframe显示预渲染的HTML
        viewer.innerHTML = `
            <iframe src="/static/uploads/${this.currentDocId}.html" 
                    style="width: 100%; height: 600px; border: none;">
            </iframe>
        `;
    }

    async exportDocument(format) {
        if (!this.currentDocId) return;

        try {
            const response = await fetch(`/api/document/${this.currentDocId}/export/${format}`);
            
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `document.${format}`;
                a.click();
                window.URL.revokeObjectURL(url);
                
                this.showSuccess(`文档已导出为 ${format.toUpperCase()} 格式`);
            } else {
                const error = await response.json();
                this.showError('导出失败：' + error.error);
            }
        } catch (error) {
            this.showError('导出失败：' + error.message);
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    showSuccess(message) {
        this.showNotification(message, 'success');
    }

    showError(message) {
        this.showNotification(message, 'danger');
    }

    showNotification(message, type = 'info') {
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        const container = document.querySelector('.container-fluid') || document.body;
        container.insertBefore(alert, container.firstChild);
        
        setTimeout(() => {
            alert.remove();
        }, 5000);
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
}

// 初始化应用
const app = new AsciiDocViewer();

// 工具函数
window.AsciiDocApp = {
    exportDocument: (docId, format) => {
        app.exportDocument(format);
    },
    
    toggleComments: () => {
        const section = document.getElementById('commentsSection');
        if (section) {
            section.style.display = section.style.display === 'none' ? 'block' : 'none';
        }
    },
    
    searchInDocument: () => {
        const query = document.getElementById('searchInput')?.value.trim();
        if (query) {
            app.performSearch(query);
        }
    }
};

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    // 获取当前文档ID
    const path = window.location.pathname;
    const match = path.match(/\/document\/([a-f0-9-]+)/);
    if (match) {
        app.currentDocId = match[1];
    }
});
